package com.uhylab.uhuvinetest.qrcamera.activity;

import android.content.Context;
import android.hardware.Camera;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;

import com.uhylab.uhuvinetest.R;
import com.uhylab.uhuvinetest.qrcamera.decode.DecodeThread;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by xyb on 16/1/9 at UHylab
 *
 * @version 1.0
 */
public class HandlerThread extends Thread {
    private Handler handler;
    private Camera camera;
    private static String string;
    private Context context;

    public HandlerThread(Context context, Handler handler, Camera camera) {
        this.handler = handler;
        this.camera = camera;
        this.context = context;
    }


    @Override
    public void run() {
        super.run();
        Looper.prepare();
        camera.takePicture(null, null, new Camera.PictureCallback() {
            @Override
            public void onPictureTaken(final byte[] data, final Camera camera) {
                try {
                    camera.startPreview(); // 拍完照后，重新开始预览
                    saveToSDCard(data); // 保存图片到sd卡中
                    Message message = Message.obtain(handler, R.id.take_pic);
                    Bundle bundle = new Bundle();
                    message.setData(bundle);
                    message.sendToTarget();
                    bundle.putString(DecodeThread.BARCODE_BITMAP, string); //将图片字节数据保存在bundle当中，实现数据交换
                    Toast.makeText(context, "保存成功!",
                            Toast.LENGTH_SHORT).show();
                } catch (IOException e) {
                    e.printStackTrace();
                    Toast.makeText(context, "请查看权限管理器,图片写入失败,请同意写入sd卡权限", Toast.LENGTH_SHORT).show();
                }
            }
        });
        Looper.loop();
    }


    /**
     * 将拍下来的照片存放在SD卡中
     *
     * @param data
     * @throws IOException
     */
    private static void saveToSDCard(byte[] data) throws IOException {
        Date date = new Date();
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss"); // 格式化时间
        String filename = format.format(date) + ".jpg";
        File fileFolder = new File(Environment.getExternalStorageDirectory()
                + "/finger/");
        if (!fileFolder.exists()) { // 如果目录不存在，则创建一个名为"finger"的目录
            fileFolder.mkdir();
        }
        File jpgFile = new File(fileFolder, filename);
        string = jpgFile.toString();
        Log.e("MainActivity", "jpgFile:" + jpgFile);
        FileOutputStream outputStream = new FileOutputStream(jpgFile); // 文件输出流
        outputStream.write(data); // 写入sd卡中
        outputStream.close(); // 关闭输出流
    }
}
